除錯Debug


程式的主要錯誤,分別為語法錯誤(rsyntax erro)、執行期間錯誤(run-time error)、和語意錯誤(semantic error)

*語法錯誤(syntax error):程式的語法有誤。

常見的語法錯誤:

  • 在 Python 中 == 才是相等,= 等號是賦值(assign)意思
    表示年齡為20歲
    #錯誤
    if age = 20 
    #正確
    if age == 20:
    
  • 格式錯誤
    空格縮排
#錯誤
if age == 20
print('可以投票')

#正確
if age == 20:
    print('你可以投票')

特殊關鍵字未加冒號(if, else...)

#錯誤
if age == 20
    print('你可以投票')

#正確
if age == 20:
    print('你可以投票')

函式、字串未正確關閉

#錯誤
print('可以投票'
#錯誤
print('可以投票)

#正確
print('可以投票')

不必要的分號Python 不用像其他程式語言需要以 ; 結尾,相對簡潔。

#錯誤
age == 20;

#正確
age == 20

*執行期間錯誤(run-time error):執行時才發生的錯誤(有些檢查對於程式語言是耗費資源的,所以才會在執行期間進行檢查,因此就會在執行期間發生錯誤)。


*語意錯誤(semantic error):又稱邏輯錯誤,發生在語法正確、程式可以執行,但結果不如預期。


*隨堂練習

#錯誤
gender == input('請輸入 male/female

if gender == 'male
    print('你是男生')
else:
    print('你不是男生)

#正確
gender = input('請輸入 male/female  ')

if gender == 'male':
    print('你是男生')
elif gender ==  'female':
    print('你是女生')
else:
    print('輸入錯誤')

https://replit.com/@kuangn22/debugquiz#main.py

內容參考:第19期Python程式設計入門共學營

#Python






你可能感興趣的文章

Secure Apache Using Certbot with Let's Encrypt on Ubuntu 20.04

Secure Apache Using Certbot with Let's Encrypt on Ubuntu 20.04

Wake On Lan 實作心得

Wake On Lan 實作心得

Nand2tetris第一週心得

Nand2tetris第一週心得






留言討論